#define DEBUG
using System;
using System.Diagnostics;

namespace Admin.NET.Application.EventMsg;

internal static class TimeOutHelper
{
	/// <summary>
	/// Returns <see cref="P:System.Environment.TickCount" /> as a start time in milliseconds as a <see cref="T:System.UInt32" />.
	/// <see cref="P:System.Environment.TickCount" /> rolls over from positive to negative every ~25 days, then ~25 days to back to positive again.
	/// <see cref="T:System.UInt32" /> is used to ignore the sign and double the range to 50 days.
	/// </summary>
	public static uint GetTime()
	{
		return (uint)Environment.TickCount;
	}

	/// <summary>
	/// Helper function to measure and update the elapsed time
	/// </summary>
	/// <param name="startTime"> The first time (in milliseconds) observed when the wait started</param>
	/// <param name="originalWaitMillisecondsTimeout">The original wait timeout in milliseconds</param>
	/// <returns>The new wait time in milliseconds, or -1 if the time expired</returns>
	public static int UpdateTimeOut(uint startTime, int originalWaitMillisecondsTimeout)
	{
		Debug.Assert(originalWaitMillisecondsTimeout != -1);
		uint elapsedMilliseconds = GetTime() - startTime;
		if (elapsedMilliseconds > int.MaxValue)
		{
			return 0;
		}
		int currentWaitTimeout = originalWaitMillisecondsTimeout - (int)elapsedMilliseconds;
		if (currentWaitTimeout <= 0)
		{
			return 0;
		}
		return currentWaitTimeout;
	}
}
